import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'package:heven/widget/button.dart';
import 'package:heven/widget/countdown.dart';
import 'package:heven/widget/input.dart';
import 'package:heven/api/index.dart';
import 'package:heven/utils/index.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:heven/widget/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String? phoneNumber; // 用户输入的手机号
  String? mobile_code;
  bool isSending = false; // 是否正在发送验证码
  late FToast fToast;
  void initState() {
    super.initState();
    fToast = FToast();
    // if you want to use context from globally instead of content we need to pass navigatorKey.currentContext!
    fToast.init(context);
  }

  // 模拟发送验证码的异步函数
  Future<bool> sendVerificationCode(String phone) async {
    var result = await sendSms({
      "mobile": phone, // 手机号
      "phone_cc": "86", // 区号
    });

    print(result);
    if (result['status'] == 200) {
      return true;
    } else {
      fToast.showToast(
        child: ToastWidget(text: result['message']),
        gravity: ToastGravity.CENTER,
      );
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Container(
          height: double.infinity,
          padding: const EdgeInsets.only(left: 22.0, right: 22.0, top: 1.0),
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomLeft,
              colors: <Color>[
                Color(0xFF060606),
                Color(0xFF145221),
              ],
            ),
          ),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const Text(
                  "手机号登录",
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22.0,
                    height: 1.6,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Text(
                  "未注册用户登录后自动创建账号",
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 11.0,
                    height: 1.3,
                  ),
                ),
                const SizedBox(
                  height: 105,
                ),
                InputWidget(
                  borderRadius: 26,
                  hintText: '请输入您的手机号码',
                  keyboardType: TextInputType.phone,
                  onChanged: (value) {
                    setState(() {
                      phoneNumber = value;
                    });
                  },
                ),
                const SizedBox(
                  height: 17,
                ),
                InputWidget(
                  borderRadius: 26,
                  hintText: '请输入验证码',
                  maxLength: 6,
                  onChanged: (value) {
                    setState(() {
                      mobile_code = value;
                    });
                  },
                  suffix: CountdownWidget(
                    phoneNumber: phoneNumber,
                    sendVerificationCode: (phone) async {
                      if (isSending) return false; // 如果正在发送，则不重复发送
                      setState(() {
                        isSending = true;
                      });

                      final success = await sendVerificationCode(phone);
                      print(success);
                      setState(() {
                        isSending = false;
                      });
                      return success;
                    },
                  ),
                ),
                const SizedBox(
                  height: 40,
                ),
                ButtonWidget(
                  margin: EdgeInsets.all(0),
                  borderRadius: 35,
                  child: const Text(
                    '登录',
                    style: TextStyle(
                      fontSize: 16,
                      color: Color(0xFF000000),
                      fontWeight: FontWeight.w800,
                    ),
                  ),
                  onTap: () async {
                    if (phoneNumber == null || mobile_code == null) {
                      // 提示用户输入完整的手机号和验证码

                      fToast.showToast(
                        child: ToastWidget(text: '请输入完整的手机号和验证码'),
                        gravity: ToastGravity.CENTER,
                      );
                      return;
                    }

                    var udid = await Common.getStorageValue('udid');
                    var uuid = await Common.getStorageValue('uuid');

                    try {
                      final loginResult = await phonelogin({
                        "mobile": phoneNumber!,
                        "phone_cc": "86",
                        "mobile_code": mobile_code!,
                        "udid": udid ?? '',
                        "uuid": uuid ?? ''
                      });
                      print(88888);
                      print(loginResult);

                      if (loginResult['status'] == 200) {
                        try {
                          await saveUser(loginResult['data'][0]);
                        } catch (e) {
                          print('ccc$e');
                        }

                        // 登录成功后跳转

                        Navigator.pushNamedAndRemoveUntil(
                          context,
                          '/home', // 你的首页路由名称
                          (route) => false, // 移除所有页面
                          arguments: {"index": 1},
                        );
                      } else {
                        String message = loginResult['message'] ?? '登录失败';
                        fToast.showToast(
                          child: ToastWidget(text: '$message'),
                          gravity: ToastGravity.CENTER,
                        );
                      }
                      print(loginResult);
                    } catch (e) {
                      fToast.showToast(
                        child: ToastWidget(text: '登录失败'),
                        gravity: ToastGravity.CENTER,
                      );
                    }
                  },
                ),
                const SizedBox(
                  height: 18,
                ),
                const Text(
                  '我已阅读并接受《用户协议》与《隐私政策》',
                  style: TextStyle(
                    fontSize: 11,
                    color: Color(0xFFE3E3E3),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
